package com.study.interecptor;

import com.alibaba.fastjson.JSON;
import com.study.Util.CommonResponse;
import com.study.Util.ServletUtil;
import com.study.annotation.RepeatSubmit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 防止重复提交拦截器
 *
 * @Author hupengming
 * @ClassName
 * @Date 2022-11-11 10:18
 * @Version 1.0
 */
@Slf4j
@Component
public abstract class RepeatSubmitInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) {
        log.info("【重复提交拦截器】");
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            RepeatSubmit annotation = handlerMethod.getMethodAnnotation(RepeatSubmit.class);
            if(annotation != null){
                if(isRepeatSubmit(request,annotation)){
                    String message = JSON.toJSONString(CommonResponse.fail(annotation.message()));
                    log.info("重复提交【message】{}",message);
                    ServletUtil.senderString(HttpServletResponse.SC_OK,response,message);
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 验证是否重复提交由子类实现具体的防重复提交的规则
     *
     * @param request
     * @param repeatSubmit
     * @return true 重复
     */
    public abstract boolean isRepeatSubmit(HttpServletRequest request,RepeatSubmit repeatSubmit);
}
